import type { App } from 'vue'
import { NRTC, NRTCEvents, NotifyCation, TRACK_TYPE, TYPE } from 'nrtc-web'
import { useNRTCHK } from '@/hooks/rtc'

export const createRTC = (app: App) => {
  const nrtc = new NRTC()
  const {
    peers,
    producers,
    consumers,
    camera,
    cameras,
    microphone,
    microphones,
    speaker,
    speakers,
    volume,
    volumes
  } = useNRTCHK()
  console.log('rtc', nrtc)
  app.config.globalProperties.$nrtc = nrtc
  app.provide('nrtc', nrtc)

  // nrtc.on()

  nrtc.on(NotifyCation.newPeer, (peer) => {
    console.log('newPeer', peer)
    peers.value[peer.peerId] = peer
  })

  nrtc.on(NotifyCation.peerClosed, (peer) => {
    console.log('peerClosed', peer)
    delete peers.value[peer.peerId]
  })

  nrtc.on(NotifyCation.newProducer, (producer) => {
    console.log('newProducer', producer)
    producers.value[producer.producerId] = producer
  })

  nrtc.on(NotifyCation.producerClosed, (producer) => {
    console.log('producerClosed', producer)
    delete producers.value[producer.producerId]
  })

  nrtc.on(NotifyCation.newConsumer, (consumer) => {
    console.log('newConsumer', consumer)
    consumers.value[consumer.consumerId] = {
      ...consumer,
      currentVolume: 0
    }
  })

  nrtc.on(NotifyCation.consumerClosed, (consumer) => {
    console.log('consumerClosed', consumer)
    delete consumers.value[consumer.consumerId]
  })

  nrtc.on(NRTCEvents.onJoinRoom, async (params) => {
    console.log('onJoinRoom', params)
    cameras.value = await NRTC.getCameraList()

    if (cameras.value.length) {
      ;[camera.value] = cameras.value
    }

    microphones.value = await NRTC.getMicrophoneList()

    if (microphones.value.length) {
      ;[microphone.value] = microphones.value
    }

    speakers.value = await NRTC.getSpeakerList()

    if (speakers.value.length) {
      ;[speaker.value] = speakers.value
    }
  })

  nrtc.on(
    NRTCEvents.onVolumeChange,
    (params: { userId: string; volume: number; producerType: TRACK_TYPE }) => {
      // console.log(NRTCEvents.onVolumeChange, params)

      if (params.userId) {
        volumes.value[params.userId] = params.volume
        // console.log('volumes', volumes.value)
      } else {
        volume.value = params.volume
      }
    }
  )

  nrtc.on(NRTCEvents.onMediaConnected, (arg) => {
    console.log(NRTCEvents.onMediaConnected, arg)
  })
}
